package dk.lobner.gwt.formvalidator.server;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;

import dk.lobner.gwt.formvalidator.client.GreetingService;
import dk.lobner.gwt.formvalidator.shared.FieldVerifier;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {


	// Verify that the input is valid. 
	boolean isLegalDate(String input) {
	    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yy");
	    sdf.setLenient(false);
	    
	    if(input.length() <= 5)
			return false;
	    if(sdf.parse(input, new ParsePosition(0)) == null)
	    	return false;
	    
	    return true;
	    
	}

	
	public String greetServer(String input) throws IllegalArgumentException {
		// Verify that the input is valid. 
		
		if (isLegalDate(input)) {
			// If the input is not valid, throw an IllegalArgumentException back to
			// the client.
			throw new IllegalArgumentException(
					"Input is not correct CPR format");
		}

		//String serverInfo = getServletContext().getServerInfo();
		//String userAgent = getThreadLocalRequest().getHeader("User-Agent");

		// Escape data from the client to avoid cross-site script vulnerabilities.
		//input = escapeHtml(input);
		//userAgent = escapeHtml(userAgent);

		//return "Hello, " + input + "!<br><br>I am running " + serverInfo
		//		+ ".<br><br>It looks like you are using:<br>" + userAgent;
		
		return input;
		//return calcValidNumbers(input);
	}

	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 * 
	 * @param html the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}
}
